from django.db import transaction
from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import Response
from cart.models import CartModel,UserModel
from rest_framework.generics import ListAPIView
from cart.cartser import CartSerializer
from utils.authorization import MyAuthentication
from order import models,orderser
from order import orderser
# Create your views here.
class CarView(ListAPIView):

    queryset = CartModel.objects.all()
    serializer_class = CartSerializer
    authentication_classes = [MyAuthentication, ]
    def get_queryset(self):
        user=self.request.query_params.get('user')
        if user:
            return self.queryset.filter(user=user,select=True)

# class CouponView(APIView):
#     def get(self,request):
#         user=request.query_params.get('user')
#         userinfo=UserModel.objects.filter(id=user).first()
#         return Response({'code':200,"msg":"请求成功","data":{"credit":userinfo.credit,"tomoney":20}})


class CouponView(APIView):
    authentication_classes = [MyAuthentication,]
    def get(self,request):
        user=request.query_params.get('user')
        userinfo=UserModel.objects.get(id=user)
        mycoupon=models.UserCoupon.objects.filter(user=user)
        ser=orderser.UserCoupon(mycoupon,many=True)
        return Response({"code":200,"msg":"请求成功","data":{"credit":userinfo.credit,"tomoney":10,"coupon":ser.data}})

from utils.myedis import redistoll
import random
import time
def get_order_number():
    order_number = str(time.strftime("%Y%m%d%H%M%S"))+str(random.randint(1000,9999))
    return order_number

class Order(APIView):
    authentication_classes = [MyAuthentication,]
    def post(self,request):
        user=request.data.get('user')
        order=redistoll.getstr(user)
        if order:
            return Response({"code":200,"msg":"你的订单已存在","data":{"orderno":order}})
        # 事务保存点
        transac=transaction.savepoint()
        try:
            orderdata = {
                "orderno": get_order_number(),
                "user": user,
                "score": request.data.get('score', 0),
                "coupon": request.data.get('coupon', None),
                "paytype": request.data.get('paytype', 1),
            }
            cart = CartModel.objects.filter(user_id=user, select=True)
            total = 0
            for i in cart:
                total += i.course.discount
            orderdata['payprice'] = total
            orderdata['totalprice'] = total
            if orderdata['score'] != 0:
                orderdata['payprice'] = float(orderdata['totalprice']) - orderdata['score'] / 10
            if orderdata['coupon'] != None:
                cou = models.UserCoupon.objects.filter(id=orderdata['coupon']).first()
                if cou.isshow:
                    orderdata['payprice'] = orderdata['totalprice'] - cou.coupon.price
            ordser = orderser.OrderCoupon(data=orderdata)
            if ordser.is_valid():
                ordser.save()
                for item in cart:
                    detail = {
                        "order": ordser.data.get('id'),
                        "course": item.course.id,
                        "price": item.course.price,
                        "discount": item.course.discount,
                        "cover": "http://127.0.0.1:8000/uploads/" + str(item.course.cover),
                        "cname": item.course.cname
                    }
                    detailser = orderser.OrderDetail(data=detail)
                    print(detailser)
                    if detailser.is_valid():
                        detailser.save()
                    else:
                        return Response(detailser.errors)
                    item.delete()
            else:
                return Response(ordser.errors)
            redistoll.delkey(user)
            transaction.savepoint_commit(transac)
            # redistoll.set(user,orderdata['orderno'],60*60)  # 60分钟过期
            return Response({"msg":"订单生成成功","id":ordser.data.get('id'),"timeoust":30})
        except Exception as e:
            transaction.savepoint_rollback(transac)
            return Response({"msg":f"订单生成失败{e}"})

# 生成支付链接
from utils.Alipay import AliPaySDK
class AliPayLInk(APIView):
    authentication_classes = [MyAuthentication,]
    def get(self,request):
        ord=request.query_params.get('order')
        order=models.OrderModel.objects.filter(id=ord).first()
        if order:
            ali=AliPaySDK()
            return Response({ali.page_pay(order.orderno,order.payprice,"浮光项目款项")})
        else:
            return Response({"msg":"订单不存在"})


class AliPayResuilt(APIView):
    def get(self,request):
        ali=AliPaySDK()
        result=ali.check_sign(request.query_params.dict())
        data=request.query_params.dict()
        if result:
            # 根据订单修改状态 支付流水 支付时间
            order=models.OrderModel.objects.filter(orderno=data.get("out_trade_no")).first()
            order.status=1
            order.payno=request.query_params.get('trade_no')
            order.paytime=request.query_params.get('timestamp')
            # 是否使用积分  使用积分 会员表见积分
            if order.score:
                user=UserModel.objects.filter(id=order.user.id).first()
                user.credit-=order.score
                user.save()
            if order.coupon:
                cou=models.UserCoupon.objects.filter(id=order.coupon).first()
                cou.isshow=False
                cou.save()
                # 是否使用优惠券 使用优惠券 修改表状态
            course=models.OrderDetailModel.objects.filter(order=order.id)
            ser=orderser.OrderDetail(course,many=True)
            return Response({"msg":"支付成功","course":ser.data,"pay_time":order.paytime,"pay_price":order.payprice})
        else:
            return Response({"msg":"支付失败"})